#!/usr/bin/env bash
#
# Summary: Verify FlexGW Dependencies.
#
# Usage: doctor
#

set -e

STATUS=0

# zip
if ! command -v zip 1>/dev/null 2>&1; then
  echo -e "FlexGW: zip is not installed.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# curl
if ! command -v curl 1>/dev/null 2>&1; then
  echo -e "FlexGW: curl is not installed.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# wget
if ! command -v wget 1>/dev/null 2>&1; then
  echo -e "FlexGW: wget is not installed.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# dmidecode
if ! command -v dmidecode 1>/dev/null 2>&1; then
  echo -e "FlexGW: dmidecode is not installed.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# openssl
if ! command -v openssl 1>/dev/null 2>&1; then
  echo -e "FlexGW: openssl is not installed.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# strongswan
if ! command -v strongswan 1>/dev/null 2>&1; then
  echo -e "FlexGW: strongswan is not installed.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# openvpn
if ! command -v openvpn 1>/dev/null 2>&1; then
  echo -e "FlexGW: openvpn is not installed.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# redirects
if sysctl -a | egrep "ipv4.*(accept|send)_redirects" | awk -F "=" '{print $2}' | grep -sqw '1' 2>/dev/null; then
  sysctl -a | egrep "ipv4.*(accept|send)_redirects" 1>&2
  echo -e "FlexGW: found error settings, please set these value to 0.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# ip_forward
if sysctl -a | grep "net.ipv4.ip_forward" | awk -F "=" '{print $2}' | grep -sqw '0' 2>/dev/null; then
  sysctl -a | grep "net.ipv4.ip_forward" 1>&2
  echo -e "FlexGW: found error settings, please set this value to 1.\n" 1>&2
  STATUS=$((STATUS+1))
fi

# result
if [ "${STATUS}" == "0" ]; then
  echo -e "\033[0;32mCongratulations! You are ready to go!\033[0m"
else
  { echo -e "\033[0;31m\033[0m"
    echo -e "\033[0;31mProblem(s) detected while checking system.\033[0m"
  } 1>&2
fi

exit "${STATUS}"
